<template>
  <div>
    <el-form
      ref="rulesform"
      :rules="rules"
      :model="userdata"
      label-width="80px"
    >
      <el-form-item label="用户名" prop="username">
        <el-input v-model="userdata.username" type="text"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="userdata.password" type="password"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="postLogin">登录</el-button>
        <el-button>取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
//引入axios
import axios from "axios";
export default {
  data() {
    return {
      userdata: {
        //v-model双向数据绑定
        username: "admin",
        password: "123456",
      },
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 3, max: 6, message: "长度在 3 到 6 个字符", trigger: "blur" },
        ],
      },
    };
  },
  mounted() {},
  methods: {
    //登录按钮事件
    postLogin() {
      this.$refs.rulesform.validate((res, rej) => {
        if (res) {
          //发送ajax请求
          this.$axios.post(`/login`, this.userdata).then((res) => {
            console.log(res);
            const { data, meta } = res.data;
            if (meta.status == 400) {
              this.$message.error({
                title: "错误",
                message: "登录失败哦",
              });
            } else if (meta.status == 200) {
              //本地存储 将后端传过来的数据进行传输到home.vue
              // localStorage.setItem('userdata',JSON.stringify(data))
              //将用户的数据通过 mutation 触发 userchange 方法 （事件 ）
              this.$store.commit("userchange", data);
              this.$message({
                title: "成功",
                message: "登录成功",
                type: "success",
              });
              this.$router.push({ path: "/Home" });
            } else {
              this.$message({
                title: "警告",
                message: "未知错误",
                type: "warning",   
              });
            }
          });
        } else {
          this.$message.error({ message: "格式错误，请输入正确的格式",});
          return false;
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
</style>